//
//  MNDBindWechatTableViewController.m
//  minidai
//
//  Created by Vitas on 2018/7/20.
//  Copyright © 2018年 迷你贷. All rights reserved.
//

#import "MNDBindWechatTableViewController.h"
#import "NSString+JKNormalRegex.h"
#import "UIButton+JKCountDown.h"
#import "MNDWechatRegistViewController.h"
#import <UMPush/UMessage.h>
#import "RSAUtil.h"

@interface MNDBindWechatTableViewController ()

@property (weak, nonatomic) IBOutlet UITextField *userPhoneTextField;
@property (weak, nonatomic) IBOutlet UILabel *phoneTipLabel;
@property (weak, nonatomic) IBOutlet UIView *phoneBottomLineView;

@property (weak, nonatomic) IBOutlet UITextField *captchaTextField;
@property (weak, nonatomic) IBOutlet UILabel *captchaTipLabel;
@property (weak, nonatomic) IBOutlet UIView *captchaBottomLineView;
@property (weak, nonatomic) IBOutlet UIButton *captchaBtn;

@property(nonatomic, assign) BOOL isSendCaptcha;

@end

@implementation MNDBindWechatTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupUI];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)setupUI {
    __weak __typeof(self)weakSelf = self;
    
    if (self.userPhone && self.userPhone.length > 0) {
        self.userPhoneTextField.text = self.userPhone;
        self.userPhoneTextField.userInteractionEnabled = NO;
    
    }
    __block UITextField *phoneTextField = self.userPhoneTextField;
    [self.userPhoneTextField.rac_textSignal subscribeNext:^(NSString * _Nullable x) {
        if (x.length > 11) {
            phoneTextField.text = [x substringToIndex:11];
        }
        if (x.length >= 11) {
            weakSelf.captchaBtn.enabled = YES;
        }else {
            weakSelf.captchaBtn.enabled = NO;
        }
    }];
    
    __block UITextField *captchaTextField = self.captchaTextField;
    [self.captchaTextField.rac_textSignal subscribeNext:^(NSString * _Nullable x) {
        if (x.length > 5) {
            captchaTextField.text = [x substringToIndex:5];
        }
    }];
    
    [self.userPhoneTextField bk_addEventHandler:^(id sender) {
        if (weakSelf.userPhoneTextField.text.length > 0) {
            weakSelf.phoneTipLabel.hidden = NO;
            weakSelf.phoneTipLabel.textColor = [UIColor colorWithRed:255/255.0 green:110/255.0 blue:63/255.0 alpha:1.0];
            weakSelf.phoneBottomLineView.backgroundColor = [UIColor colorWithRed:255/255.0 green:110/255.0 blue:63/255.0 alpha:1.0];
        }else {
            weakSelf.phoneTipLabel.hidden = YES;
        }
        
    } forControlEvents:UIControlEventEditingChanged];
    
    [self.userPhoneTextField bk_addEventHandler:^(id sender) {
        if(weakSelf.userPhoneTextField.text.length <= 0) {
            weakSelf.phoneTipLabel.hidden = YES;
        }
        weakSelf.phoneTipLabel.textColor = [UIColor colorWithRed:203/255.0 green:203/255.0 blue:203/255.0 alpha:1.0];
        weakSelf.phoneBottomLineView.backgroundColor = [UIColor colorWithRed:239/255.0 green:239/255.0 blue:244/255.0 alpha:1.0];
    } forControlEvents:UIControlEventEditingDidEnd];
    
    [self.captchaTextField bk_addEventHandler:^(id sender) {
        
        if (weakSelf.captchaTextField.text.length > 0) {
            weakSelf.captchaTipLabel.hidden = NO;
            weakSelf.captchaTipLabel.textColor = [UIColor colorWithRed:255/255.0 green:110/255.0 blue:63/255.0 alpha:1.0];
            weakSelf.captchaBottomLineView.backgroundColor = [UIColor colorWithRed:255/255.0 green:110/255.0 blue:63/255.0 alpha:1.0];
        }else {
            weakSelf.captchaTipLabel.hidden = YES;
        }
        
    } forControlEvents:UIControlEventEditingChanged];
    
    [self.captchaTextField bk_addEventHandler:^(id sender) {
        if(weakSelf.captchaTextField.text.length <= 0) {
            weakSelf.captchaTipLabel.hidden = YES;
        }
        weakSelf.captchaTipLabel.textColor = [UIColor colorWithRed:203/255.0 green:203/255.0 blue:203/255.0 alpha:1.0];
        weakSelf.captchaBottomLineView.backgroundColor = [UIColor colorWithRed:239/255.0 green:239/255.0 blue:244/255.0 alpha:1.0];
    } forControlEvents:UIControlEventEditingDidEnd];
}

//发送验证码
- (IBAction)sendPhoneCaptchaAction:(id)sender {
    
    kdeclare_weakself;
    [self.view endEditing:YES];
    if (self.userPhoneTextField.text.length <= 0) {
        [NetworkProgressHUD showHudMsg:@"请输入手机号"];
        return;
    }
    
    [NetworkProgressHUD showHud];
    
    [APIManager sendRequestWithPath:API_SEND_PHONE_CAPTCHA parameters:[MNDSign signedParamWithDict:@{@"user_phone": self.userPhoneTextField.text}] method:kXMHTTPMethodPOST onSuccess:^(ResponseModel *responseModel) {
        
        if (responseModel.status == ResponseSuccess) {
            [weakSelf.captchaBtn jk_startTime:30 title:@"重新获取" waitTittle:@"秒后重发"];
            [NetworkProgressHUD showHudMsg:@"验证码已发送"];
            weakSelf.isSendCaptcha = YES;
        } else {
            NSDictionary *dict = responseModel.msg;
            if (dict && dict.count > 0) {
                [NetworkProgressHUD showHudMsg:dict[@"error"]];
            } else {
                [NetworkProgressHUD showHudMsg:@"发送失败，请重新发送"];
            }
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}
//微信绑定
- (IBAction)confirmAction:(UIButton *)sender {
    if (!self.isSendCaptcha) {
        [NetworkProgressHUD showHudMsg:@"请先获取手机验证码"];
        return;
    }
    
    if (self.userPhoneTextField.text <= 0) {
        [NetworkProgressHUD showHudMsg:@"请输入手机号码"];
        return;
    }
    if (self.captchaTextField.text.length <= 0) {
        [NetworkProgressHUD showHudMsg:@"请输入验证码"];
        return;
    }
    
    kdeclare_weakself;
    [NetworkProgressHUD showHud];
    NSDictionary *dict = @{
                           @"user_phone":self.userPhoneTextField.text,
                           @"phone_captcha":self.captchaTextField.text,
                           @"unionid":self.user.credential.rawData[@"unionid"],
                           @"open_type": @"1"
                           };
    [APIManager sendRequestWithURL:API_WECHAT_BIND parameters:[MNDSign signedParamWithDict:dict] method:kXMHTTPMethodPOST onSuccess:^(ResponseModel *responseModel) {
        [NetworkProgressHUD hideHud];
        if (responseModel.status == ResponseSuccess) {
            NSString *str = responseModel.data[@"is_register"];
            if (str.integerValue == 1) {//is_register  1需要去注册，-1不需要去注册
                [weakSelf goWechatRegist];
            }else {
//                if (!self.isUserCenterEnter) {
//                    [NetworkProgressHUD showHudMsg:responseModel.msg[@"success"]];
//                }
                
                if (weakSelf.isUserCenterEnter) {
                    
                    [self.navigationController popViewControllerAnimated:YES];
                }else {
                    MNDLoginUserModel *userModel = [MNDLoginUserModel mj_objectWithKeyValues:responseModel.data];
                    //更新数据库
                    [MNDLoginUserModel addOrUpdateUser:userModel];
                    //设置用户标识
                    [Bugly setUserIdentifier:userModel.user_id];
                    
                    [weakSelf setHTTPHeaders];
                    
                    //设置消息推送别名
                    [UMessage setAlias:userModel.user_code type:@"minidai" response:^(id  _Nonnull responseObj, NSError * _Nonnull error) {
                        if (error) {
                            NSLog(@"设置别名失败: %@", error);
                        } else {
                            NSLog(@"设置别名成功: %@", responseObj);
                        }
                    }];
                    [weakSelf dismissViewControllerAnimated:YES completion:nil];
                }
                [NetworkProgressHUD showHudMsg:@"绑定成功"];
            }
            
        }else {
            [NetworkProgressHUD showHudMsg:responseModel.msg[@"error"]];
        }
        
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

- (void)goWechatRegist {
    MNDWechatRegistViewController *registVC = [UIStoryboard viewControllerWithIdentifier:@"MNDWechatRegistViewController"];
    registVC.user = self.user;
    registVC.userPhone = self.userPhoneTextField.text;
    [self.navigationController pushViewController:registVC animated:YES];
}

- (void)setHTTPHeaders {
    //传userCode
    MNDLoginUserModel *user = [MNDLoginUserModel currentLoginUser];
    if (user.user_code.length > 0) {
        NSString *encryText = [RSAUtil encryptString:[NSString stringWithFormat:@"%@", user.user_code] publicKey:RSA_PUBLIC_KEY];
        NSString *unreserved = @"";
        NSMutableCharacterSet *allowed = [NSMutableCharacterSet alphanumericCharacterSet];
        [allowed addCharactersInString:unreserved];
        
        NSString *encodeEncryText = [encryText stringByAddingPercentEncodingWithAllowedCharacters:allowed];
        [APIManager setGeneralHeaderValue:encodeEncryText forField:@"USERCODE"];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


/*
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:<#@"reuseIdentifier"#> forIndexPath:indexPath];
    
    // Configure the cell...
    
    return cell;
}
*/

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
